package com.example.demo.controller;

import com.example.demo.beans.Result;
import com.example.demo.beans.entity.DemoSysMenu;
import com.example.demo.service.MenuService;
import com.example.demo.util.CommUtil;
import com.example.demo.util.StringUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@RestController
@RequestMapping("/sysConfig")
public class SysConfigController {
    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    MenuService menuService;

    @RequestMapping("/addMenus")
    public Result addMenus(String paramStr){
        try{
            log.info("新增菜单：{}",paramStr);

            List<DemoSysMenu> datas = mapper.readValue(paramStr,new TypeReference<List<DemoSysMenu>>(){});
            if(CommUtil.isListNotBlank(datas)){
                datas.stream().forEach(item -> {
                    if(item.getF_ParentId() == 0){
                        menuService.addOrUpdateDemoSysMenu(item);
                    }
                });
            }

        }catch (Exception e){
            log.error("",e);
        }

        return new Result(false,"新增菜单出错");
    }

    @RequestMapping("/getMenus")
    public Result getMenus(){
        try{
            log.info("查询所有的菜单");

            List<DemoSysMenu> menus = menuService.getAllMenus();

            return new Result(true,menus);

        }catch (Exception e){
            log.error("",e);
        }

        return new Result(false,"查询菜单出错");
    }

    @RequestMapping("/loadHtml")
    public Result loadHtml(@RequestParam("path") String path){
        try {
            log.info("加载html,path:"+path);

            if(StringUtil.isBlank(path)){
                return new Result(false);
            }

            Map data = new HashMap();
            String html = CommUtil.getContent(path);
            data.put("html",html);

            return new Result(true,data);

        }catch (Exception e){
            log.error("",e);
        }

        return new Result(false,"加载html出错");
    }
}
